/*
 * FILE     :  QuotaApi.java
 *
 * CLASS    :  QuotaApi
 *
 * COPYRIGHT:
 *
 *   The computer systems, procedures, data bases and programs
 *   created and maintained by Qware Technology Group Co Ltd, are proprietary
 *   in nature and as such are confidential.  Any unauthorized
 *   use or disclosure of such information may result in civil
 *   liabilities.
 *
 *   Copyright Mar 4, 2015 by Qware Technology Group Co Ltd.
 *   All Rights Reserved.
*/
package com.cfweb.api;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.cfweb.controller.LoginHandler;
import com.cfweb.util.CloudFoundryClientUtil;
import com.cfweb.util.JsonUtil;

public class QuotaApi {
	/**
	 * name
	 * non_basic_services_allowed
	 * total_services
	 * total_routes
	 * memory_limit
	 * instance_memory_limit
	 * 
	 * @param session
	 * @param params
	 * @throws Exception
	 */
	public static void createQuota(HttpSession session,HashMap<String, Object> params) throws Exception{
		String host=((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		String url=host+"/v2/quota_definitions";
		CloudFoundryClientUtil.doCCPost(url, params, session);
	}
	
	/**
	 * async	Will run the delete request in a background job. Recommended: 'true'.
	 * @param session
	 * @param guid
	 * @throws Exception
	 */
	public static void deleteQuota(HttpSession session,String guid) throws Exception{
		String host=((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		String url=host+"/v2/quota_definitions/"+guid;
		CloudFoundryClientUtil.doCCDelete(url, null, session);
	}
	
	public static List<Map<String,Object>> getQuotas(HttpSession session,String name) throws Exception{
		String host=((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		String url=host+"/v2/quota_definitions";
		if(name!=null){
			url=url+"?q=name:"+name;
		}
		String content=CloudFoundryClientUtil.doCCGet(url, null, session);
		Map<String, Object> data = JsonUtil.convertJsonToMap(content);
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> lr = (List<Map<String, Object>>) data.get("resources");
		String nextUrl = (String) data.get("next_url");
		while (nextUrl != null) {
			nextUrl = ApiCommonUtil.retriveAllPageResource(lr, nextUrl, session);
		}
		return lr;
	}
	
	/**
	 * name
	 * non_basic_services_allowed
	 * total_services
	 * total_routes
	 * memory_limit
	 * instance_memory_limit
	 * 
	 * @param session
	 * @param params
	 * @throws Exception
	 */
	public static void updateQuota(HttpSession session,String guid,HashMap<String, Object> params) throws Exception{
		String host=((URL)session.getAttribute(LoginHandler.TARGET)).toString();
		String url=host+"/v2/quota_definitions/"+guid;
		CloudFoundryClientUtil.doCCPut(url, params, session);
	}
}
